package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"path"
	"time"
)

var (
	config     Config
	logs       *log.Logger
	configFile = flag.String("c", "conf/conf.yaml", "配置文件")
	logFile    = flag.String("l", "logs/log.txt", "日志文件")
)

func init() {

	flag.Usage = func() {
		fmt.Printf("Usage %s -c=conf/conf.yaml -l log.txt", os.Args[0])
		flag.PrintDefaults()
	}
	flag.Parse()

	if err := config.ParseConfigFile(*configFile); err != nil {
		fmt.Printf("%s\n%s", "Unable to load config info!", err)
		os.Exit(1)
	}

}

func main() {

	//runWeather()
	os.MkdirAll(path.Dir(*logFile), 0666)
	if logPath, err := os.OpenFile(*logFile, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666); err == nil {
		defer logPath.Close()
		logs = log.New(logPath, "[info]", log.Ldate|log.Ltime)
		fmt.Println("the service is running")
	} else {
		fmt.Println(err)
	}

	acSlice := ApiInit()
	for i := 0; i < len(acSlice); i++ {
		os.MkdirAll(path.Dir(acSlice[i].Path), 0666)
		acSlice[i].HandleInit()
		go acSlice[i].run()
	}

	http.HandleFunc("/reload", func(w http.ResponseWriter, r *http.Request) {
		logs.Println(r.RemoteAddr, "accessed /cmd/reload")
		for i := 0; i < len(acSlice); i++ {
			if acSlice[i].Method {
				(acSlice[i].Con).Stop()
			}
		}
		logs.Println("all api are closed")
		config.ParseConfigFile(*configFile)
		acSlice = ApiInit()
		for i := 0; i < len(acSlice); i++ {
			os.MkdirAll(path.Dir(acSlice[i].Path), 0666)
			go acSlice[i].run()
		}
		logs.Println("all api are opened")

		fmt.Fprintln(w, time.Now(), "api reload complete")
	})

	http.HandleFunc("/list", func(w http.ResponseWriter, r *http.Request) {
		logs.Println(r.RemoteAddr, "accessed /cmd/list")
		fmt.Fprintln(w, "the API list:")
		for i := 0; i < len(acSlice); i++ {
			if acSlice[i].Method {
				fmt.Fprintln(w, acSlice[i].Name, "Request Url:", acSlice[i].Url, "cron status:", acSlice[i].Con.GetRunning(), ";cronrate:", acSlice[i].Cronrate)
			} else {
				fmt.Fprintln(w, acSlice[i].Name, "Request Url:", acSlice[i].Url)
			}
		}
	})

	http.HandleFunc("/run", func(w http.ResponseWriter, r *http.Request) {
		names := r.URL.Query()["name"]
		if names != nil {
			for i := 0; i < len(names); i++ {
				for j := 0; j < len(acSlice); j++ {
					if acSlice[j].Name == names[i] {
						if acSlice[j].Name == "zwzx_qlqd" {
							acSlice[j].writeSzrx()
						} else if acSlice[j].Name == "szrx" {
							acSlice[j].writeSzrx()
						} else {
							acSlice[j].writeApiJson()
						}
					}
				}
			}
		} else {
			for j := 0; j < len(acSlice); j++ {
				if acSlice[j].Name == "zwzx_qlqd" {
					go acSlice[j].writeSzrx()
				} else if acSlice[j].Name == "szrx" {
					go acSlice[j].writeSzrx()
				} else {
					go acSlice[j].writeApiJson()
				}
			}
		}
	})
	fmt.Println("running API list:")
	for i := 0; i < len(acSlice); i++ {
		if acSlice[i].Method {
			fmt.Println(acSlice[i].Name, "Request Url:", acSlice[i].Url, ";cronrate:", acSlice[i].Cronrate)
		} else {
			fmt.Println(acSlice[i].Name, "Request Url:", acSlice[i].Url)
		}
	}
	http.ListenAndServe("127.0.0.1:"+config.Bind, nil)
}
